import datetime
from application import db
from sqlalchemy import *
import hashlib
from common.Secret import make_uuid
from jwt import encode
from flask import current_app
from apps.front.models import FrontUser,ProductType
class User(db.Model):

    __tablename__ = 'user'

    id = db.Column(Integer, primary_key=True, autoincrement=True, doc='用户主键')
    nick_name = db.Column(String(length=50), nullable=False, default='暂无昵称', doc='用户昵称')
    login_name = db.Column(String(length=64), nullable=False, unique=True, doc='登陆名')
    login_pwd = db.Column(String(length=128), nullable=False, doc='用户登陆密码')
    login_slot = db.Column(String(length=128), nullable=False)
    avatar = db.Column(String(length=128), nullable=False, default='/static/img/default_male.png', doc='用户头像')
    sex = db.Column(Integer, default=1, nullable=False, doc='用户性别 1男 2女')
    area = db.Column(String(length=128), default='暂无地区', nullable=False, doc='用户的所属地区')
    wx_number = db.Column(String(length=128), nullable=False, default='', doc='用户的微信账号')
    create_time = db.Column(DateTime, nullable=False, default=datetime.datetime.now, doc='注册时间')
    update_time = db.Column(DateTime, nullable=False, default=datetime.datetime.now, onupdate=datetime.datetime.now,
                            doc='修改时间')
    status = db.Column(Integer, nullable=False, default=1, doc='1：用户可用，2：用户不可用')

    def __init__(self, *args, **kwargs):

        if 'login_slot' not in kwargs and len(args) < 4:
            kwargs.setdefault('login_slot', make_uuid())
        super(User, self).__init__(*args, **kwargs)

    def protectPassWord(self):
        slot_str = '%s**%s' % (self.login_pwd, self.login_slot)
        md5 = hashlib.md5()
        md5.update(slot_str.encode('utf-8'))
        new_pwd = md5.hexdigest()
        self.login_pwd = new_pwd

    def checkPassWord(self, password):
        slot_str = '%s**%s' % (password, self.login_slot)
        md5 = hashlib.md5()
        md5.update(slot_str.encode('utf-8'))
        pwd = md5.hexdigest()
        if pwd == self.login_pwd:
            return True
        return False

    def __setattr__(self, key, value):
        super(User, self).__setattr__(key, value)
        if key == 'login_slot':
            self.protectPassWord()

    def get_jwt_str(self):
        
        jwt_str = encode(payload={
            'exp':datetime.datetime.utcnow() + current_app.config['JWT_EXP'],
            'user_id':self.id,
            'user_type': 'admin',
            'avatar':self.avatar,
            'nick_name':self.nick_name
        },key=current_app.config['SECRET_KEY'])
        return jwt_str.decode('utf-8')



class ShareHistory(db.Model):
    __tablename__ = 'share_history'

    id = db.Column(Integer, primary_key=True, autoincrement=True)
    name = db.Column(String(length=300),nullable=False, default=0, doc='分享人')
    share_number = db.Column(Integer, nullable=False, default=0, doc='分享人数')
    create_time = db.Column(DateTime, default=datetime.datetime.now, doc='建立时间')
    content = db.Column(String(length=500), nullable=False,doc='内容')


class OperationHistory(db.Model):
    __tablename__ = 'operation_history'
    id = db.Column(Integer, primary_key=True, autoincrement=True)
    action = db.Column(String(length=300), nullable=False,doc='操作内容')
    title = db.Column(String(length=128), nullable=False, doc='标题')
    create_time = db.Column(DateTime, nullable=False, default=datetime.datetime.now, doc='申请时间')
    user_id = db.Column(Integer, db.ForeignKey(User.id, ondelete='RESTRICT'), doc='用户外建')
    user = db.relationship(User, backref=db.backref('operation_history', lazy='dynamic'), cascade='all')

class Order2Product(db.Model):

    __tablename__ = 'order_2_product'
    id = db.Column(Integer, primary_key=True, autoincrement=True)
    product_id = db.Column(Integer,db.ForeignKey(ProductType.id, ondelete='RESTRICT'),doc='商品')
    order_id = db.Column(Integer,db.ForeignKey('orders.id', ondelete='RESTRICT'),doc='订单')
    number = db.Column(Integer,doc='数量')
    email = db.Column(String(length=300),nullable=False,default=make_uuid,doc='邮件')
    product = db.relationship(ProductType,backref=db.backref('Sales'),cascade='all')
    order = db.relationship("Order",backref='products',cascade='all')

class UseNumber(db.Model):

    __tablename__ = 'use_number'

    id = db.Column(Integer, primary_key=True, autoincrement=True)
    is_use = db.Column(Boolean,nullable=False,default=False,doc='是否使用')
    card_number = db.Column(String(length=300),nullable=False,default=make_uuid,doc='激活号')
    order_product_id = db.Column(Integer,db.ForeignKey(Order2Product.id, ondelete='RESTRICT'),doc='关联商品')
    Order2Product = db.relationship(Order2Product,backref='usenumber',cascade='all')


class Order(db.Model):

    __tablename__ = 'orders'

    id = db.Column(Integer,primary_key=True,autoincrement=True)
    create_time = db.Column(DateTime,nullable=False,default=datetime.datetime.now)
    update_time = db.Column(DateTime,nullable=False,default=datetime.datetime.now,onupdate=datetime.datetime.now)
    pay_number = db.Column(DECIMAL(10,2),nullable=False,doc='订单金额')
    pay_channels = db.Column(Integer,nullable=False,default=1,doc='1 微信，2支付宝，，支付渠道')
    is_pay  = db.Column(Boolean,nullable=False,default=False,doc='是否支付')
    order_number = db.Column(String(length=300),nullable=False,default=make_uuid,doc='订单号')
    pay_time = db.Column(DateTime,nullable=True,doc='支付时间')
    trade_no = db.Column(String(length=300),nullable=True,default=make_uuid,doc='支付宝或者微信订单号')
    user_id = db.Column(Integer,db.ForeignKey(FrontUser.id, ondelete='RESTRICT'),nullable=True,doc='用户')
    user = db.relationship(FrontUser,backref=db.backref('orders',uselist=False),cascade='all')
    is_distribution = db.Column(Boolean,nullable=False,default=False,doc='是否是分销商订单')
    distribution = db.Column(String(length=300),nullable=False,default='',doc='分销商')




class Setting(db.Model):

    __tablename__ = 'setting'

    id = db.Column(Integer,primary_key=True,autoincrement=True)
    logo = db.Column(String(length=128), nullable=False, default='', doc='网站logo')
    qq_number = db.Column(String(length=128), nullable=False, default='', doc='qq')
    wechat_number = db.Column(String(length=128), nullable=False, default='', doc='wechat')
    wechat_qrcode = db.Column(String(length=128), nullable=False, default='', doc='wechatqrcode')
    level_1_price = db.Column(DECIMAL(10,2),nullable=False,doc='一级分销商价格')
    level_1 = db.Column(DECIMAL(10,2),nullable=False,doc='一级分销商提成')
    level_2_price = db.Column(DECIMAL(10,2),nullable=False,doc='二级分销商价格')
    level_2 = db.Column(DECIMAL(10,2),nullable=False,doc='二级分销商提成')
    level_3_price = db.Column(DECIMAL(10,2),nullable=False,doc='三级分销商价格')
    level_3 = db.Column(DECIMAL(10,2),nullable=False,doc='三级分销商提成')